//
//  YYERechargeViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2018/1/5.
//  Copyright © 2018年 胡波. All rights reserved.
//

#import "YYERechargeViewController.h"
#import "YYERechargeTableViewCell.h"
#import "YYERechargeMoneyTableViewCell.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "WXApiObject.h"
#import "NSStringExt.h"
#import "PayModel.h"


@interface YYERechargeViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) YYEBaseTableView *tableView;
@property(nonatomic,strong) NSString *payType;
@property (nonatomic,strong) UITextField *moneyTF;


@end

@implementation YYERechargeViewController

static NSString * paymentCell = @"payment";
static NSString * moneyCell = @"moneyCell";

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"充值";
    
    [self configUI];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.payType = @"wechat";

    });

    
    //支付成功通知事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess) name:@"kPaySuccessNotification" object:nil];
    
}

- (void)paySuccess
{
    
    //充值或提现成功通知事件
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kchargeOrDepositSuccessNotification" object:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)configUI {
    
    [self.view addSubview:self.tableView];
    
    self.tableView.backgroundColor = GeneralBackColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [self footeView];
    
    [self.tableView registerClass:[YYERechargeTableViewCell class] forCellReuseIdentifier:paymentCell];
    [self.tableView registerClass:[YYERechargeMoneyTableViewCell class] forCellReuseIdentifier:moneyCell];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];

    
}

- (UIView *)footeView {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 69)];
    contentView.backgroundColor = GeneralBackColor;
    
    UIButton *rechargeBtn = [[UIButton alloc]init];
    [rechargeBtn setTitle:@"确认充值" forState:UIControlStateNormal];
    [rechargeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rechargeBtn setBackgroundColor:GeneralBlueColor];
    rechargeBtn.layer.cornerRadius = 5;
    [rechargeBtn addTarget:self action:@selector(rechargeClicked) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:rechargeBtn];
    
    [rechargeBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView.left).offset(30);
        make.right.equalTo(contentView.right).offset(-30);
        make.top.equalTo(contentView.top).offset(27);
        make.height.equalTo(42);
    }];
    
    return contentView;
    
}

// 确认充值
- (void)rechargeClicked {
    
    if (_moneyTF.text.length == 0) {
        [self.view makeToast:@"请输入金额"];
        return;
    }
    
    NSMutableDictionary *paramDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    [paramDic setValue:[LoginModel shareLogin].uid forKey:@"uid"];
    [paramDic setValue:[LoginModel shareLogin].token forKey:@"token"];
    [paramDic setValue:[LoginModel shareLogin].username forKey:@"username"];

    
    // 1支付宝 2微信
    if ([self.payType isEqualToString:@"wechat"]) {
        [paramDic setValue:[NSString getIPAddress:YES] forKey:@"spbill_create_ip"];
    }
    else {
        
    }
    [paramDic setValue:self.payType forKey:@"type"];
    [paramDic setValue:_moneyTF.text forKey:@"money"];

    [AFNHelper post:Recharge parameters:paramDic success:^(id responseObject) {
        
        if ([responseObject[@"status"] isEqual:@1]) {
            // 1支付宝 2微信
            
            PayModel *model = [PayModel mj_objectWithKeyValues:responseObject[@"data"][@"info"]];

            if ([responseObject[@"data"][@"type"] integerValue] == 1) {


            }
            else if ([responseObject[@"data"][@"type"] integerValue] == 2) {

                //需要创建这个支付对象
                PayReq *req = [[PayReq alloc] init];
                //应用id
                req.openID = model.appid;

                // 商家商户号
                req.partnerId = model.partnerid;

                // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
                req.prepayId = model.prepayid;//self.orderWithWX.prepayid;

                // 根据财付通文档填写的数据和签名
                //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
                req.package = model.package;

                // 随机编码，为了防止重复的，在后台生成
                req.nonceStr = model.noncestr;//self.orderWithWX.noncestr;

                // 这个是时间戳，也是在后台生成的，为了验证支付的
                int timesta = [model.timestamp intValue];
                UInt32 timestamp = (UInt32)timesta;
                req.timeStamp = timestamp;

                // 这个签名也是后台做的
                req.sign = model.sign;//self.orderWithWX.sign;

                //发送请求到微信，等待微信返回onResp
                [WXApi sendReq:req];


            }

        }
        else {
            [self.view makeToast:responseObject[@"message"]];
        }
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        
    }];
}

- (YYEBaseTableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[YYEBaseTableView alloc]initwithDelegate:self];
    }
    return _tableView;
    
}

#pragma mark -- UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
//        return 2;
        return 1;

    }else {
        return 1;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        YYERechargeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:paymentCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSArray *names = @[@"微信支付",@"支付宝支付"];
        NSArray *imgNames = @[@"weixin",@"zhifubao"];
        
        cell.nameLabel.text = names[indexPath.row];
        cell.headerIV.image = [UIImage imageNamed:imgNames[indexPath.row]];
        cell.row = indexPath.row;
        cell.block = ^(NSInteger row) {
            
            if (row == 0) {
                self.payType = @"wechat";
            }
            else {
                self.payType = @"alipay";

            }
        };
        
        if (indexPath.row == 1) {
            cell.lineView.hidden = YES;
        }
        
        return cell;
        
    }else {
        
        YYERechargeMoneyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:moneyCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.nameLabel.text = @"充值金额";
        self.moneyTF = cell.moneyTF;
        return cell;
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    
    contentView.backgroundColor = GeneralBackColor;
    
    return contentView;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 10;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
